﻿using System.ComponentModel;
using System.Text;
using System.Web;
using System.Net;

namespace N2.Web.Handlers
{
	using ComponentModel;
	using Newtonsoft.Json;

	public class JsonHandler: IHttpHandler
	{
		#region IHttpHandler Members

		bool IHttpHandler.IsReusable { get { return false; } }

		void IHttpHandler.ProcessRequest(HttpContext context)
		{
			int _id = 0;

			if (!int.TryParse(context.Request.QueryString["id"], out _id) || _id == 0) {
				context.Response.End();
				return;
			}

			var _item = Context.Current.Persister.Get(_id);

			if (null == _item) {
				context.Response.StatusCode = (int)HttpStatusCode.NotFound;
				context.Response.End();
				return;
			}

			if (!_item.IsAuthorized(context.User)) {
				context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
				context.Response.End();
				return;
			}

			context.Response.ContentType = "application/x-javascript";
			context.Response.ContentEncoding = Encoding.UTF8;
			context.Response.Cache.SetCacheability(HttpCacheability.Public);
			
			TypeDescriptor.AddProvider(
				new JsonContentItemTypeDescriptionProvider(),
				typeof(ContentItem));

			var _serializer = new JsonSerializer {
				ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
			};

			_serializer.Serialize(
				context.Response.Output,
				_item);
			
			//Jayrock.Json.Conversion.Converters.ComponentExporter.ResolveCircularReference += (_sender, _e) => {
			//    var _value = _e.OriginalValue as ContentItem;
			//    if (null != _value) {
			//        _e.NewValue = "$ref: " + _value.Url;
			//    }
			//};
			
			//Jayrock.Json.Conversion.JsonConvert.Export(_item, context.Response.Output);

			context.Response.End();
		}

		#endregion
	}
}
